package com.four.seckill.config;

import com.four.seckill.dao.SeckillMapper;
import com.four.seckill.entity.Seckill;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 *
 * 项目启动后运行
 * @author 刘阳
 * @email 1991512948@qq.com
 * @date 2021-12-09 20:36:50
 */
@Component
public class AppRunit implements ApplicationRunner {

    @SuppressWarnings("all")
    @Autowired
    private SeckillMapper pmsSeckillProductDao;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 项目启动redis放入所有秒杀商品以及对应的库存
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        /**
         * 雪崩问题 加随机数
         */
        Random random = new Random();
        int i = random.nextInt(300000);

        List<Seckill> pmsSeckillProductEntities = pmsSeckillProductDao.selectList(null);
        for (Seckill pmsSeckillProductEntity : pmsSeckillProductEntities) {
            Integer seckillId = pmsSeckillProductEntity.getSeId();
            Integer limitedNum = pmsSeckillProductEntity.getSeLimitSurplus();
            redisTemplate.opsForValue().set("seckill:serviceimpl" + seckillId.toString(),limitedNum,300000+i, TimeUnit.MILLISECONDS);
        }


    }


}
